package phases

import (
	"fmt"

	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

	bkev1beta1 "gopkg.openfuyao.cn/cluster-api-provider-bke/api/v1beta1"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/pkg/phaseframe"
	v "gopkg.openfuyao.cn/cluster-api-provider-bke/version"
)

const (
	EnsureFinalizerName confv1beta1.BKEClusterPhase = "EnsureFinalizer"
)

type EnsureFinalizer struct {
	phaseframe.BasePhase
}

func NewEnsureFinalizer(ctx *phaseframe.PhaseContext) phaseframe.Phase {
	base := phaseframe.NewBasePhase(ctx, EnsureFinalizerName)
	return &EnsureFinalizer{base}
}

func (e *EnsureFinalizer) Execute() (_ ctrl.Result, err error) {
	controllerutil.AddFinalizer(e.Ctx.BKECluster, bkev1beta1.ClusterFinalizer)
	e.Ctx.Log.Info("VERSION", "-----------------Start Reconcile BKECluster-----------------------")
	e.Ctx.Log.Info("VERSION", fmt.Sprintf("BKE Version     : %s", v.Version))
	e.Ctx.Log.Info("VERSION", fmt.Sprintf("BKE GitCommitId : %s", v.GitCommitID))
	e.Ctx.Log.Info("VERSION", fmt.Sprintf("BKE Architecture: %s", v.Architecture))
	e.Ctx.Log.Info("VERSION", fmt.Sprintf("BKE BuildTime   : %s", v.BuildTime))
	e.Ctx.Log.Info("VERSION", "------------------------------------------------------------------")
	return ctrl.Result{}, nil
}

func (e *EnsureFinalizer) NeedExecute(old *bkev1beta1.BKECluster, new *bkev1beta1.BKECluster) (needExecute bool) {
	if controllerutil.ContainsFinalizer(new, bkev1beta1.ClusterFinalizer) {
		e.SetStatus(bkev1beta1.PhaseSkipped)
		return false
	}
	e.SetStatus(bkev1beta1.PhaseWaiting)
	return true
}
